package gui.chatarea;

import java.awt.Component;
import java.io.File;
import java.util.HashSet;

import file.TransferFile;
import gui.userslist.UserTargetedListener;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.HTML;

import utils.Utils;

import controller.MessageController;

public class ChatHyperLinkListener implements HyperlinkListener {

	private final UserTargetedListener userTargetedListener ;
	private final MessageController messController ;
	private final Component parent ;

	public ChatHyperLinkListener (Component parent, UserTargetedListener usl, MessageController messController) {
		this.userTargetedListener = usl ;
		this.messController = messController ;
		this.parent = parent ;
	}
	
	@Override
	public void hyperlinkUpdate(HyperlinkEvent e) {
		if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) {
			SimpleAttributeSet anchor = (SimpleAttributeSet)e.getSourceElement().getAttributes().getAttribute(HTML.Tag.A) ;
			String href = (String) anchor.getAttribute(HTML.Attribute.HREF) ;
			String id = (String) anchor.getAttribute(HTML.Attribute.ID) ;
			String cl = (String)anchor.getAttribute(HTML.Attribute.CLASS) ;
			if (HTMLChatDocument.URL_LINK_CLASS.equals(cl)) {
				Utils.openURL(href) ;
			}
			else if (HTMLChatDocument.FILE_LINK_CLASS.equals(cl)) {
				// Utils.openFile(href) ;
			}
			else if (HTMLChatDocument.USER_LINK_CLASS.equals(cl)) {
				HashSet <String> ids = new HashSet <String> () ;
				ids.add(href) ;
				this.userTargetedListener.usersTargeted (ids) ;
			}
			else if (HTMLChatDocument.TRANSFER_FILE_LINK_CLASS.equals(cl)) {
				TransferFile tf = this.messController.getWaitingToAcceptFile(href);
				try {
					if (Boolean.valueOf(id)) {
						JFileChooser jfc = new JFileChooser() ;
						jfc.setSelectedFile(new File(tf.getFileName())) ;
						if (jfc.showSaveDialog(this.parent) != JFileChooser.APPROVE_OPTION) {
							this.messController.sendFileRefused(tf) ;
						}
						else {
							this.messController.sendFileAccepted(new TransferFile(tf, jfc.getSelectedFile().getAbsolutePath())) ;
						}
					}
					else {
						this.messController.sendFileRefused(tf) ;
					}
				}
				catch (Exception ex) {
					// ex.printStackTrace() ;
					JOptionPane.showMessageDialog(this.parent, "Erreur durant l'envoi de la réponse.", "Erreur de transfert", JOptionPane.ERROR_MESSAGE) ;
				}
			}
		}	
	}

}
